//
//  JCPlanViewController.m
//  JiFengDaRen
//
//  Created by shouhan on 2018/3/30.
//  Copyright © 2018年 陈永发. All rights reserved.
//

#import "JCPlanViewController.h"
#import "JCPlanCell.h"
#import "JCPlanView.h"
#import "SHNerAreaList.h"
#import "SexPickerView.h"
#import "JCPickerView.h"
#import "JCPlanFootView.h"
#import "JCAddressPickerView.h"
#import "JCPlanWebViewController.h"

#import "JCPlanTableViewCell.h"
#import "JCPlanHeadView.h"

@interface JCPlanViewController ()<UITableViewDelegate,UITableViewDataSource,addBtnActionDelegate,JCPickerViewDelegate,planCellDelegate>
{
    NSInteger indexCount;
}
@property (nonatomic, strong) UITableView * planTableView;

@property (nonatomic, strong) JCPlanFootView * planFootView;// 区尾

@property (nonatomic, strong) JCPickerView *dateView;//时间选择器
@property (nonatomic, strong) SexPickerView * sexPickerView;

@property (nonatomic, strong) NSMutableDictionary * dicHead;
@property (nonatomic, strong) NSMutableDictionary * dicRepayment;
@property (nonatomic, strong) NSString * strType;
@property (nonatomic, strong) NSString * strProvince;
@property (nonatomic, strong) NSString * strCity;
@property (nonatomic, strong) NSString * strDateString;
@property (nonatomic, strong) NSMutableArray * arrCity;

@property (nonatomic, strong) NSMutableArray * arrAmount;//金额

@property (nonatomic, strong) NSMutableArray * arrRepayItem;

@property (nonatomic, strong) NSMutableArray * arrTime;

@property (nonatomic, assign) BOOL isClean;

@end


static NSString * const JPHeaderId = @"JCPlanHeadView";

@implementation JCPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置还款计划";
    
    self.view.backgroundColor = KBASEBGCOLOR;
   
    self.strType = @"小额落地商户";
    self.strProvince = @"";
    self.strCity = @"";
    self.strDateString = @"";
    indexCount = 0;
    self.isClean = NO;
    
    [self.arrAmount addObject:@""];
    self.arrTime = [NSMutableArray array];
    [self DoRequsetArea];
    
    [self planTableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addSubAction:) name:@"addSub" object:nil];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return self.arrAmount.count;
    }else{
        return [self.dicRepayment[@"titleName"][section] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        JCPlanCell * cell = [JCPlanCell tableViewCellWithTableView:tableView];
        if (indexPath.row == 0) {
            cell.deleteBtn.hidden = YES;
        }else{
            cell.deleteBtn.hidden = NO;
        }
        
        cell.index = indexPath.row + 100;
        cell.delegate = self;
        cell.deleteBtn.tag = 100+indexPath.row;
        cell.amount.tag = 100+indexPath.row;

        [cell getIndexNumber:indexPath.row];
        
        cell.manageModel = self.model;
        
        if (self.isClean == YES) {
            [cell getAmountText:self.arrAmount[indexPath.row]];
        }
        
        return cell;

    }else{
        JCPlanTableViewCell * cell = [JCPlanTableViewCell tableViewCellWithTableView:tableView];
    
        [cell getPlanRepayment:self.dicRepayment andSection:indexPath.section andIndexRow:indexPath.row];
        return cell;
    }
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        return __I6Height(90);
    }else{
        return __I6Height(50);
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return nil;
    }else{
        JCPlanHeadView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:JPHeaderId];
        header.delegate = self;
        header.addBtn.tag = 200+section;
        [header getHeadTitle:self.dicHead andIndex:section-1];
        
        return header;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
        }else if (indexPath.row == 1) {
//            [self popTypeView];
            self.isClean = YES;
        }else {
            if (self.arrCity.count > 0) {
                [JCAddressPickerView showWithDataArray:self.arrCity block:^(NSString *province, NSString *city) {
                    self.strProvince = province;
                    self.strCity = city;
                    [self.dicRepayment setValue:@[@[self.model.cardNo,self.strType,province,city],@[@""]] forKey:@"contentName"];
                    self.isClean = NO;
                    [self.planTableView reloadData];
                }];
            }else{
                [self.view makeToast:@"正在维护" duration:2.f position:@"center"];
            }

        }
    }else if (indexPath.section == 1){
        [self popDateView];
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 44;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

#pragma mark - 懒加载
- (UITableView *)planTableView{
    
    if (!_planTableView) {
        _planTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - KNAVIGATIONBARHEIGHT) style:UITableViewStylePlain];
        _planTableView.delegate = self;
        _planTableView.dataSource = self;
        _planTableView.backgroundColor = KBASEBGCOLOR;
        [_planTableView registerClass:[JCPlanHeadView class] forHeaderFooterViewReuseIdentifier:JPHeaderId];
        self.planFootView = [[JCPlanFootView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, __I6Height(100))];
        [self.planTableView setTableFooterView:self.planFootView];
        [self.view addSubview:_planTableView];
    }
    return _planTableView;
    
}

- (NSMutableArray *)arrCity{
    if (!_arrCity) {
        _arrCity = [NSMutableArray array];
    }
    return _arrCity;
}

- (NSMutableArray *)arrAmount{
    if (!_arrAmount) {
        _arrAmount = [NSMutableArray array];
    }
    return _arrAmount;
}
- (NSMutableArray *)arrRepayItem{
    if (!_arrRepayItem) {
        _arrRepayItem = [NSMutableArray array];
    }
    return _arrRepayItem;
}

- (NSMutableDictionary *)dicHead{
    if (!_dicHead) {
        _dicHead = [NSMutableDictionary dictionaryWithObjectsAndKeys:@[@"当前还款订单",@"当前还款订单数"],@"titleName",@[@"添加下一天还款订单",@""],@"contentName", nil];
    }
    return _dicHead;
}

- (NSMutableDictionary *)dicRepayment{
    if (!_dicRepayment) {
        _dicRepayment = [NSMutableDictionary dictionaryWithObjectsAndKeys:@[@[@"还款卡号",@"还卡类别",@"落地商户所属省份",@"落地商户所属城市"],@[@"还款时间"]],@"titleName",@[@[self.model.cardNo,self.strType,self.strProvince,self.strCity],@[self.strDateString]],@"contentName", nil];
    }
    return _dicRepayment;
}

- (void)clickAddBtnAction:(UIButton *)btn{
    
    if (btn.tag == 201) {
        [self getRepayItem];
        
    }else{
        indexCount ++;
        if ([self.strType isEqualToString:@"大额还款"]) {
            if (indexCount>2) {
                indexCount = 2;
            }else{
            
                [self.arrAmount addObject:@""];
            }
        }else{
            if (indexCount>2) {
                indexCount = 2;
            }else{
                [self.arrAmount addObject:@""];
            }
        }
        self.isClean = YES;
        [self.planTableView reloadData];
    }
}

// 得到订单
- (void)getRepayItem{
    NSMutableDictionary * dictItem = [NSMutableDictionary dictionary];
    if ([self.strDateString isEqualToString:@""]) {
        [self.view makeToast:@"请选择还款时间" duration:2.f position:@"center"];
    }else{
        
        if ([self.arrTime containsObject:self.strDateString]) {
            NSLog(@"是否覆盖");
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定要覆盖当天的还款订单吗" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction * defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self.arrAmount enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isEqualToString:@""]) {
                        *stop = YES;
                        if (*stop == YES) {
                            [self.arrAmount removeObject:obj];
                        }
                    }else{
                        CGFloat money = ([obj doubleValue] - [self.model.fee doubleValue] *0.01)/(1+[self.model.rate doubleValue]);
                        [self.arrAmount replaceObjectAtIndex:idx withObject:[NSString stringWithFormat:@"%.2f",money]];
                    }
                }];
                if (self.arrAmount.count>0) {
                    NSString * str = [self.arrAmount componentsJoinedByString:@","];
                    [dictItem setValue:str forKey:@"amount"];
                    [dictItem setValue:self.strDateString forKey:@"repay_time"];
                    [self.arrRepayItem addObject:dictItem];
                    self.isClean = YES;
                }
                
                [self.arrAmount removeAllObjects];
                [self.arrAmount addObject:@""];
                [self.planTableView reloadData];
                indexCount = 0;
            }];
            
            UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.view makeToast:@"请重新选择还款时间" duration:2.f position:@"center"];
            }];
            [alert addAction:defaultAction];
            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else{
            
            [self.arrAmount enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isEqualToString:@""]) {
                    *stop = YES;
                    if (*stop == YES) {
                        [self.arrAmount removeObject:obj];
                    }
                }else{
                    CGFloat money = ([obj doubleValue] - [self.model.fee doubleValue] *0.01)/(1+[self.model.rate doubleValue]);
                    [self.arrAmount replaceObjectAtIndex:idx withObject:[NSString stringWithFormat:@"%.2f",money]];
                }
            }];
            if (self.arrAmount.count > 0) {
                [self.arrTime addObject:self.strDateString];
                [dictItem setObject:[self.arrAmount componentsJoinedByString:@","] forKey:@"amount"];
                [dictItem setObject:self.strDateString forKey:@"repay_time"];
                
                self.isClean = YES;
                [self.arrRepayItem addObject:dictItem];
            }
        }
        
        [self.arrAmount removeAllObjects];
        [self.arrAmount addObject:@""];
        [self.planTableView reloadData];
        indexCount = 0;
    }
    
}

- (void)getAmountText:(NSString *)strMoney andIndex:(NSInteger)index{
    [self.arrAmount replaceObjectAtIndex:index-100 withObject:strMoney];
}


- (void)clickDeleteAction:(UIButton *)btn{
    
    indexCount--;
    if (btn.tag>100) {
        [self.arrAmount removeObjectAtIndex:btn.tag-100];
    }

    self.isClean = YES;
    [self.planTableView reloadData];
}


- (void)popTypeView{
    
    self.sexPickerView = [[SexPickerView alloc] init];
    __weak typeof(self) weakSelf = self;

    self.sexPickerView.dataSource =@[@"小额落地商户",@"大额还款"];
    self.sexPickerView.valueDidSelect = ^(NSString *value){
        if ([value isEqualToString:@"大额还款"]) {
            [weakSelf.dicRepayment setValue:@[@[@"还款卡号",@"还卡类别"],@[@"还款时间"]] forKey:@"titleName"];
        }else{
            [weakSelf.dicRepayment setValue:@[@[@"还款卡号",@"还卡类别",@"落地商户所属省份",@"落地商户所属城市"],@[@"还款时间"]] forKey:@"titleName"];
        }
        weakSelf.strType = value;
        [weakSelf.dicRepayment setValue:@[@[weakSelf.model.cardNo,weakSelf.strType,weakSelf.strProvince,weakSelf.strCity],@[weakSelf.strDateString]] forKey:@"contentName"];
        indexCount = 0;
        [weakSelf.arrAmount removeAllObjects];
        [weakSelf.arrAmount addObject:@""];
        [weakSelf.arrTime removeAllObjects];
        [weakSelf.arrRepayItem removeAllObjects];
        [weakSelf.planTableView reloadData];
    };
    [weakSelf.sexPickerView show];
}

// 弹出时间选择器
- (void)popDateView{
    self.dateView= [[JCPickerView alloc] initDatePickerWithDefaultDate:nil andDatePickerMode:UIDatePickerModeDate];
    self.dateView.delegate = self;
    self.dateView.datePicker.minimumDate = [NSDate date];
    [self.dateView show];
}

#pragma mark -- 时间选择器delegate
- (void)pickerView:(JCPickerView *)pickerView didSelectDateString:(NSString *)dateString{
    self.strDateString = dateString;
    [self.dicRepayment setValue:@[@[self.model.cardNo,self.strType,self.strProvince,self.strCity],@[self.strDateString]] forKey:@"contentName"];
    self.isClean = NO;
    [self.planTableView reloadData];
}

- (void)addSubAction:(NSNotification *)tag{

    if ([self.strDateString isEqualToString:@""]) {
        [self.view makeToast:@"请选择还款时间" duration:2.f position:@"center"];
        return;
    }else if ([self.strProvince isEqualToString:@""] && [self.strType isEqualToString:@"1"] ){
        [self.view makeToast:@"请选择银行卡所属省份" duration:2.f position:@"center"];
        return;
    }else if ([self.strCity isEqualToString:@""] && [self.strType isEqualToString:@"1"]){
        [self.view makeToast:@"请选择银行卡所属城市" duration:2.f position:@"center"];
        return;
    }
//    else if (self.arrRepayItem.count == 0){
//        [self.view makeToast:@"请添加还款订单" duration:2.f position:@"center"];
//    }
    else{
        [self DoRequsetCreatePlan];
    }
}


// 获取落地支持区域
- (void)DoRequsetArea{

    [PPNetworkHelper GET:H_down_area parameters:@{@"cooperator_user_id":self.model.cooperator_user_id} cache:NO encrypt:NO decode:NO responseCache:^(id responseCache) {

    } success:^(id result) {

        if ([result[@"success"] boolValue] == 1) {
            NSDictionary * dic = [NSDictionary dictionaryWithDictionary:result[@"data"]];
            NSMutableArray * arrPC = [NSMutableArray array];
            for (NSDictionary * dicPro in dic[@"provinceList"]) {
                NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                NSMutableArray * cityArr = [NSMutableArray array];

                for (NSDictionary * dicCity in dic[@"cityList"]) {
                    if ([dicPro[@"id"] isEqualToString:dicCity[@"parentId"]]) {
                        [cityArr addObject:dicCity];
                    }
                    [dict setObject:cityArr forKey:@"cities"];
                    [dict setObject:dicPro[@"value"] forKey:@"name"];
                }

                [arrPC addObject:dict];
            }

            NSMutableArray *nmArray = [NSMutableArray arrayWithCapacity:arrPC.count];
            for (NSDictionary *dic in arrPC) {
                [nmArray addObject:[city citiesWithDic:dic]];
            }
            [self.arrCity removeAllObjects];
            [self.arrCity addObjectsFromArray:nmArray];

        }else{
            [self.view  makeToast:result[@"data"] duration:2.f position:@"center"];
        }

    } failure:^(NSError *error) {

    }];

}


- (void)DoRequsetCreatePlan{
    
    [self getRepayItem];
    
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setValue:self.model.cardNo forKey:@"cardNo"];
    NSString * typeStr;
    if ([self.strType isEqualToString:@"小额落地商户"]) {
        typeStr = @"1";
    }else{
        typeStr = @"0";
    }
    [dict setValue:typeStr forKey:@"channel_type"];

    [dict setValue:self.arrRepayItem forKey:@"repayItemList"];
    [dict setValue:self.strProvince forKey:@"province_name"];
    [dict setValue:self.strCity forKey:@"city_name"];

    NSString *deviceUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [dict setValue:deviceUUID forKey:@"device_id"];

    [PPNetworkHelper POST:H_create_repay_plan parameters:dict cache:NO encrypt:YES decode:YES responseCache:^(id responseCache) {

    } success:^(id result) {
        if ([result[@"success"] boolValue] == YES) {

            if ([result[@"data"][@"status"] boolValue] == NO) {

                NSString * html = [result[@"data"][@"page"] base64DecodedString];

                JCPlanWebViewController * web = [[JCPlanWebViewController alloc] init];
                web.url = html;
                [self.navigationController pushViewController:web animated:YES];
            }else{

                [self.navigationController popViewControllerAnimated:YES];
            }

        }else{
            [self.view makeToast:result[@"data"] duration:2.f position:@"center"];
        }

    } failure:^(NSError *error) {

    }];

}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
